package jdbc.transaction_;

import jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @author DCSGO
 * @version 1.0
 * 转账问题--事务
 */
public class Transaction_ {
    //模拟马云向马化腾转账 100 元
    //不使用事务
    @Test
    public void noTransaction() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            String sql1 = "update `account` set balance = balance - 100 where id = 1";
            String sql2 = "update `account` set balance = balance + 100 where id = 2";
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            //模拟转账过程中出现了错误
            int a = 10 / 0;

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }
        //java.lang.ArithmeticException: / by zero
        //马云的余额扣了100但马化腾的余额却没有变
    }

    //使用事务
    @Test
    public void transaction() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            String sql1 = "update `account` set balance = balance - 100 where id = 1";
            String sql2 = "update `account` set balance = balance + 100 where id = 2";
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);//关闭自动提交
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            //模拟转账过程中出现了错误
            //int a = 10 / 0;

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            connection.commit();
        } catch (Exception e) {
            //捕获到异常
            System.out.println("000000");
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }
        //000000
        //java.lang.ArithmeticException: / by zero
        //两个人的余额都没变
        //屏蔽错误后两人的余额正确更新
    }
}
